<template>
  <div class="fee-details">
    <div class="page-header">
      <div class="header-content">
        <h1>挂号缴费清单</h1>
        <div class="patient-info" v-if="appointmentInfo.patientName">
          <span class="patient-name">{{ appointmentInfo.patientName }}</span>
          <span class="patient-id"
            >ID: {{ appointmentInfo.patientId || "N/A" }}</span
          >
        </div>
      </div>
      <div class="action-buttons">
        <el-button class="back-button" @click="goBack" size="large">
          <el-icon><Back /></el-icon>
          返回上一步
        </el-button>
      </div>
    </div>

    <div class="content-layout">
      <div class="main-content">
        <div
          class="payment-mode"
          :class="{ 'self-pay': paymentMode === 'selfpay' }"
        >
          <el-icon class="mode-icon">
            <component :is="paymentMode === 'insurance' ? User : Money" />
          </el-icon>
          <div class="mode-info">
            <span class="mode-text">
              {{ paymentMode === "insurance" ? "职工医保支付" : "自费支付" }}
              <span
                v-if="useInsurance && paymentMode === 'insurance'"
                class="insurance-tag"
              >
                (生育保险)
              </span>
            </span>
            <div class="mode-subtext" v-if="paymentMode === 'insurance'">
              当前账户余额: ¥{{ insuranceBalance.toFixed(2) }}
            </div>
          </div>
        </div>

        <div class="card fee-card">
          <div class="card-header">
            <el-icon class="card-header-icon"><Document /></el-icon>
            <span>费用明细</span>
          </div>

          <div class="table-container">
            <table class="fee-table">
              <thead>
                <tr>
                  <th class="fee-name-col">项目名称</th>
                  <th class="fee-amount-col">金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in feeItems" :key="index">
                  <td class="fee-name">{{ item.name }}</td>
                  <td class="fee-amount">¥{{ item.amount.toFixed(2) }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div class="total-row">
            <span class="total-label">费用合计：</span>
            <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
          </div>

          <template v-if="paymentMode === 'insurance'">
            <div class="insurance-section">
              <div class="section-title">
                <el-icon><User /></el-icon>
                <span>医保结算</span>
              </div>
              <div class="insurance-table">
                <div
                  class="insurance-row"
                  v-for="(row, index) in insuranceSettlementRows"
                  :key="index"
                >
                  <span class="insurance-name">{{ row.name }}</span>
                  <span class="insurance-value">{{ row.value }}</span>
                </div>
              </div>
            </div>
          </template>
        </div>

        <div class="security-tips">
          <el-icon class="security-icon"><Lock /></el-icon>
          <span>支付安全保证，您的信息不会泄露</span>
        </div>
      </div>

      <div class="sidebar">
        <div class="summary-card">
          <div class="summary-header">
            <el-icon><CreditCard /></el-icon>
            <span>支付摘要</span>
          </div>

          <div class="summary-content">
            <div class="summary-row">
              <span>支付方式</span>
              <span class="payment-type">
                {{ paymentMode === "insurance" ? "医保支付" : "自费支付" }}
                <span
                  v-if="useInsurance && paymentMode === 'insurance'"
                  class="insurance-badge"
                  >生育保险</span
                >
              </span>
            </div>

            <div class="summary-row">
              <span>费用总额</span>
              <span>¥{{ totalAmount.toFixed(2) }}</span>
            </div>

            <template v-if="paymentMode === 'insurance'">
              <div class="summary-row" v-if="!useInsurance">
                <span>医保支付</span>
                <span class="insurance-pay"
                  >-¥{{ insurancePayment.toFixed(2) }}</span
                >
              </div>
            </template>

            <div class="summary-divider"></div>

            <div class="summary-row total-payable">
              <span>应付金额</span>
              <span class="payable-amount"
                >¥{{ payableAmount.toFixed(2) }}</span
              >
            </div>
          </div>

          <div v-if="showSelfPaymentTip" class="alert-box">
            <el-icon class="alert-icon"><Warning /></el-icon>
            <div class="alert-content">
              <div class="alert-title">医保账户余额不足</div>
              <div class="alert-desc">
                需自费支付 ¥{{ selfPaymentAmount.toFixed(2) }}
              </div>
            </div>
          </div>

          <div
            v-if="useInsurance && paymentMode === 'insurance'"
            class="success-box"
          >
            <el-icon class="success-icon"><CircleCheck /></el-icon>
            <div class="success-content">
              <div class="success-title">生育保险已启用</div>
              <div class="success-desc">覆盖全部费用，实际支付 0 元</div>
            </div>
          </div>

          <div class="payment-actions">
            <el-button
              type="primary"
              size="large"
              @click="confirmPayment"
              :loading="confirming"
              class="confirm-button"
            >
              <template v-if="!confirming">
                <el-icon><CreditCard /></el-icon>
                确认支付 ¥{{ payableAmount.toFixed(2) }}
              </template>
              <template v-else> 支付处理中... </template>
            </el-button>

            <el-button class="help-button" size="large" @click="showHelp">
              <el-icon><QuestionFilled /></el-icon>
              需要帮助
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { User, Money } from "@element-plus/icons-vue";
//引入格式化工具
import { PaymentDataFormatter } from "@/utils/paymentDataFormatter";
// 调用后端API接口
import { addRegistration } from "@/api/api.js";

const props = defineProps({
  appointmentInfo: {
    type: Object,
    required: true,
    default: () => ({
      patientName: "张某某",
      patientId: "P20240012345",
      department: "内科",
      doctor: "王医生",
      time: "2024-01-15 10:30",
    }),
  },
  paymentMode: {
    type: String,
    required: true,
  },
  useInsurance: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["confirm-payment", "back", "help"]);

const confirming = ref(false);

// 费用项目
const feeItems = ref([
  { name: "挂号费", amount: props.appointmentInfo.fee || 0.5 },
]);

// 医保相关数据
const insuranceBalance = ref(256.0);
const insuranceRatio = ref(0.55); // 55%报销比例

// 计算属性
const totalAmount = computed(() => {
  const total = feeItems.value.reduce((sum, item) => sum + item.amount, 0);
  return Math.round(total * 100) / 100; // 保留两位小数
});

// 医保可报销金额
const reimbursableAmount = computed(() => {
  const amount = totalAmount.value * insuranceRatio.value;
  return Math.round(amount * 100) / 100; // 保留两位小数
});

// 医保实际支付金额（不超过账户余额）
const insurancePayment = computed(() => {
  const payment = Math.min(insuranceBalance.value, reimbursableAmount.value);
  return Math.round(payment * 100) / 100; // 保留两位小数
});

// 自费支付金额
const selfPaymentAmount = computed(() => {
  if (props.paymentMode === "selfpay") {
    return Math.round(totalAmount.value * 100) / 100;
  }

  // 如果使用生育保险且是妇产科，费用为0
  if (props.useInsurance) {
    return 0;
  }

  const selfPay = Math.max(0, totalAmount.value - insurancePayment.value);
  return Math.round(selfPay * 100) / 100; // 保留两位小数
});

// 应付金额（自费部分）
const payableAmount = computed(() => {
  return Math.round(selfPaymentAmount.value * 100) / 100; // 保留两位小数
});

// 是否显示自费支付提示
const showSelfPaymentTip = computed(() => {
  return (
    props.paymentMode === "insurance" &&
    !props.useInsurance &&
    insurancePayment.value < reimbursableAmount.value
  );
});

// 医保结算行数据
const insuranceSettlementRows = computed(() => {
  if (props.useInsurance) {
    return [
      { name: "医保账户余额", value: `¥${insuranceBalance.value.toFixed(2)}` },
      { name: "生育保险状态", value: "已启用" },
      { name: "保险覆盖金额", value: `¥${totalAmount.value.toFixed(2)}` },
      { name: "医保实际支付", value: `¥${totalAmount.value.toFixed(2)}` },
    ];
  }

  return [
    { name: "医保账户余额", value: `¥${insuranceBalance.value.toFixed(2)}` },
    {
      name: "医保报销比例",
      value: `${(insuranceRatio.value * 100).toFixed(0)}%`,
    },
    {
      name: "医保可报销金额",
      value: `¥${reimbursableAmount.value.toFixed(2)}`,
    },
    { name: "医保实际支付", value: `¥${insurancePayment.value.toFixed(2)}` },
  ];
});

// 生成挂号编号
const generateAppointmentId = () => {
  const now = new Date();
  const year = now.getFullYear().toString(); // 年份四位
  const month = (now.getMonth() + 1).toString().padStart(2, "0"); // 月份
  const day = now.getDate().toString().padStart(2, "0"); // 日期
  const dateStr = year + month + day; // 年月日

  // 生成6位随机数
  const randomNum = Math.floor(100000 + Math.random() * 900000).toString();

  return `TJ${dateStr}${randomNum}`;
};

// 确认支付
const confirmPayment = async () => {
  confirming.value = true;

  // 生成挂号编号
  const appointmentId = generateAppointmentId();

  // 计算医保报销金额（与显示一致）
  const insuranceDeductionAmount = insurancePayment.value;
  // 获取患者信息
  const currentPatient = JSON.parse(
    localStorage.getItem("currentPatient") || "{}"
  );

  // 准备提交给后端的数据
  const paymentData = {
    // 挂号编号
    appointmentId: appointmentId,

    // 患者信息
    patientInfo: {
      name: props.appointmentInfo.patientName,
      id: props.appointmentInfo.patientId,
      insurance_card_number: currentPatient.cardNumber, // 关键修改
      // 可以从 localStorage 获取更多患者信息
      ...JSON.parse(localStorage.getItem("currentPatient") || "{}"),
    },

    // 挂号信息
    appointmentInfo: {
      department_id: props.appointmentInfo.department_id,
      department: props.appointmentInfo.department_name,
      doctor_id: props.appointmentInfo.doctor_id,
      doctor: props.appointmentInfo.doctor,
      time: props.appointmentInfo.time,
      room: props.appointmentInfo.room,
      fee: props.appointmentInfo.fee,
      // 添加医保报销金额
      insuranceDeduction: insuranceDeductionAmount,
      schedule_instance_id: props.appointmentInfo.schedule_instance_id, // 新增
    },

    // 支付信息
    paymentInfo: {
      mode: props.paymentMode, // 'insurance' 或 'selfpay'
      useInsurance: props.useInsurance,
      totalAmount: totalAmount.value,
      insurancePayment: insurancePayment.value,
      selfPayment: selfPaymentAmount.value,
      payableAmount: payableAmount.value,
      insuranceBalance: insuranceBalance.value,
      // 同时在这里也设置一份，确保能传递到后续组件
      insuranceDeduction: insuranceDeductionAmount,
    },

    // 费用明细
    feeItems: feeItems.value,

    // 时间戳
    timestamp: new Date().toISOString(),
    paymentTime: new Date().toLocaleString("zh-CN"),
  };

  // 验证数据完整性
  PaymentDataFormatter.validatePaymentData(paymentData);

  // 格式化数据为后端需要的结构
  const formattedData = PaymentDataFormatter.formatToBackend(paymentData);

  console.log("格式化后的后端数据:", formattedData);

  // ============== 提交挂号信息（未缴费）============
  const registrationResponse = await addRegistration(formattedData);
  console.log("挂号接口响应:", registrationResponse);

  if (registrationResponse && registrationResponse.code === 200) {
    confirming.value = false;
    emit("confirm-payment", {
      amount: payableAmount.value,
      paymentMode: props.paymentMode,
      useInsurance: props.useInsurance,
      // 添加完整数据用于后续步骤
      paymentData: paymentData,
    });
    console.log("挂号信息提交成功:", registrationResponse.msg);
  } else {
    return;
  }
};

// 返回上一页
const goBack = () => {
  emit("back");
};

// 显示帮助
const showHelp = () => {
  emit("help");
};
</script>

<style lang="scss" scoped>
.fee-details {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  padding: 24px;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;

  .header-content {
    h1 {
      margin: 0 0 12px 0;
      color: #1e293b;
      font-size: 32px;
      font-weight: 700;
    }

    .patient-info {
      display: flex;
      align-items: center;
      gap: 20px;

      .patient-name {
        font-size: 18px;
        color: #475569;
        font-weight: 600;
      }

      .patient-id {
        font-size: 16px;
        color: #64748b;
        background: #f1f5f9;
        padding: 4px 12px;
        border-radius: 8px;
      }
    }
  }
}

.content-layout {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 24px;
  align-items: start;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.payment-mode {
  display: flex;
  align-items: center;
  padding: 28px;
  border-radius: 16px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);

  &.self-pay {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    box-shadow: 0 8px 25px rgba(16, 185, 129, 0.3);
  }

  .mode-icon {
    margin-right: 20px;
    font-size: 32px;
    flex-shrink: 0;
  }

  .mode-info {
    flex: 1;
  }

  .mode-text {
    display: block;
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 8px;
  }

  .mode-subtext {
    font-size: 16px;
    opacity: 0.9;
    font-weight: 500;
  }
}

.insurance-tag {
  background: rgba(255, 255, 255, 0.2);
  padding: 6px 12px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  margin-left: 12px;
}

.card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  border: 1px solid #e2e8f0;
}

.fee-card {
  .card-header {
    display: flex;
    align-items: center;
    padding: 24px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-bottom: 1px solid #e2e8f0;
    font-weight: 600;
    color: #1e293b;
    font-size: 20px;

    .card-header-icon {
      margin-right: 12px;
      color: #3b82f6;
      font-size: 24px;
    }
  }
}

.table-container {
  padding: 0 24px;
}

.fee-table {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;

  thead {
    background: #f8fafc;

    th {
      padding: 16px 12px;
      text-align: left;
      font-weight: 600;
      color: #475569;
      border-bottom: 2px solid #e2e8f0;
      font-size: 16px;
    }
  }

  tbody tr {
    border-bottom: 1px solid #f1f5f9;
    transition: background-color 0.2s;

    &:hover {
      background: #f8fafc;
    }

    &:last-child {
      border-bottom: none;
    }
  }

  td {
    padding: 20px 12px;
    vertical-align: middle;
  }
}

.fee-name {
  color: #374151;
  font-weight: 500;
  font-size: 16px;
}

.fee-amount {
  text-align: right;
  font-weight: 600;
  color: #1f2937;
  font-size: 16px;
}

.total-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
  font-size: 18px;
  font-weight: 600;

  .total-label {
    color: #475569;
  }

  .total-amount {
    color: #1f2937;
    font-size: 20px;
  }
}

.insurance-section {
  padding: 24px;
  border-top: 1px dashed #e2e8f0;

  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    font-size: 18px;
    font-weight: 600;
    color: #1e293b;

    .el-icon {
      margin-right: 10px;
      color: #3b82f6;
    }
  }
}

.insurance-table {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.insurance-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;

  .insurance-name {
    color: #64748b;
    font-weight: 500;
  }

  .insurance-value {
    color: #3b82f6;
    font-weight: 600;
  }
}

.sidebar {
  position: sticky;
  top: 24px;
}

.summary-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
  overflow: hidden;
}

.summary-header {
  display: flex;
  align-items: center;
  padding: 24px;
  background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
  color: white;
  font-size: 20px;
  font-weight: 700;

  .el-icon {
    margin-right: 12px;
    font-size: 24px;
  }
}

.summary-content {
  padding: 24px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  font-size: 16px;

  &:not(:last-child) {
    border-bottom: 1px solid #f1f5f9;
  }

  .payment-type {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .insurance-badge {
    background: #dbeafe;
    color: #1d4ed8;
    padding: 2px 8px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 600;
  }

  .insurance-pay {
    color: #10b981;
    font-weight: 600;
  }
}

.summary-divider {
  height: 2px;
  background: linear-gradient(
    90deg,
    transparent 0%,
    #e2e8f0 50%,
    transparent 100%
  );
  margin: 20px 0;
}

.total-payable {
  font-size: 20px;
  font-weight: 700;

  .payable-amount {
    color: #ef4444;
    font-size: 24px;
  }
}

.alert-box,
.success-box {
  margin: 0 24px 24px;
  padding: 20px;
  border-radius: 12px;
  display: flex;
  align-items: flex-start;
  gap: 12px;

  .alert-icon,
  .success-icon {
    font-size: 20px;
    flex-shrink: 0;
    margin-top: 2px;
  }
}

.alert-box {
  background: #fffbeb;
  border: 1px solid #fcd34d;
  color: #92400e;

  .alert-icon {
    color: #f59e0b;
  }

  .alert-title {
    font-weight: 600;
    margin-bottom: 4px;
  }

  .alert-desc {
    font-size: 14px;
    opacity: 0.9;
  }
}

.success-box {
  background: #f0fdf4;
  border: 1px solid #bbf7d0;
  color: #166534;

  .success-icon {
    color: #22c55e;
  }

  .success-title {
    font-weight: 600;
    margin-bottom: 4px;
  }

  .success-desc {
    font-size: 14px;
    opacity: 0.9;
  }
}

.payment-actions {
  padding: 0 24px 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.confirm-button {
  height: 64px;
  font-size: 18px;
  font-weight: 700;
  border-radius: 12px;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;

  &:hover:not(:disabled) {
    background: linear-gradient(135deg, #059669 0%, #047857 100%);
    transform: translateY(-2px);
    box-shadow: 0 12px 30px rgba(16, 185, 129, 0.4);
  }

  &:active {
    transform: translateY(0);
  }
}

.help-button {
  height: 56px;
  font-size: 16px;
  border-radius: 12px;
  border: 1px solid #d1d5db;
  background: white;
  color: #6b7280;

  &:hover {
    background: #f9fafb;
    border-color: #9ca3af;
  }
}

.security-tips {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  color: #475569;
  font-weight: 500;
  border: 1px solid #e2e8f0;

  .security-icon {
    margin-right: 12px;
    color: #3b82f6;
    font-size: 20px;
  }
}

.back-button {
  background: white;
  color: #475569;
  border: 1px solid #d1d5db;
  height: 52px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 500;
  padding: 0 24px;

  &:hover {
    background: #f9fafb;
    border-color: #9ca3af;
    transform: translateY(-1px);
  }
}

/* 平板端适配 */
@media (max-width: 1024px) {
  .content-layout {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .sidebar {
    position: static;
  }

  .page-header {
    padding: 20px;

    h1 {
      font-size: 28px;
    }
  }

  .payment-mode {
    padding: 24px;

    .mode-text {
      font-size: 20px;
    }
  }
}

/* 手机端适配 */
@media (max-width: 768px) {
  .fee-details {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
    padding: 20px;
    margin-bottom: 20px;

    .header-content {
      h1 {
        font-size: 24px;
        margin-bottom: 8px;
      }

      .patient-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
      }
    }
  }

  .payment-mode {
    padding: 20px;
    flex-direction: column;
    text-align: center;
    gap: 12px;

    .mode-icon {
      margin-right: 0;
      margin-bottom: 8px;
    }

    .mode-text {
      font-size: 18px;
    }
  }

  .card-header {
    padding: 20px;
    font-size: 18px;
  }

  .table-container {
    padding: 0 16px;
  }

  .fee-table {
    td,
    th {
      padding: 16px 8px;
      font-size: 14px;
    }
  }

  .total-row {
    padding: 20px;
    font-size: 16px;

    .total-amount {
      font-size: 18px;
    }
  }

  .summary-header {
    padding: 20px;
    font-size: 18px;
  }

  .summary-content {
    padding: 20px;
  }

  .summary-row {
    font-size: 15px;
    padding: 14px 0;
  }

  .payment-actions {
    padding: 0 20px 20px;
  }

  .confirm-button {
    height: 56px;
    font-size: 16px;
  }

  .help-button {
    height: 48px;
  }
}

/* 小屏手机适配 */
@media (max-width: 480px) {
  .fee-details {
    padding: 12px;
  }

  .page-header {
    padding: 16px;

    h1 {
      font-size: 22px;
    }
  }

  .payment-mode {
    padding: 16px;

    .mode-text {
      font-size: 16px;
    }
  }

  .insurance-tag {
    font-size: 14px;
    padding: 4px 8px;
  }

  .fee-table {
    td,
    th {
      padding: 12px 6px;
      font-size: 13px;
    }
  }

  .alert-box,
  .success-box {
    margin: 0 16px 16px;
    padding: 16px;
  }
}

/* 自助机大屏优化 */
@media (min-width: 1280px) {
  .fee-details {
    padding: 32px;
    max-width: 1400px;
    margin: 0 auto;
  }

  .content-layout {
    grid-template-columns: 1fr 450px;
  }

  .confirm-button {
    height: 70px;
    font-size: 20px;
  }

  .payment-mode {
    .mode-text {
      font-size: 26px;
    }

    .mode-subtext {
      font-size: 18px;
    }
  }
}
</style>